/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.security.validate2;

import cn.nkpro.elcube.security.UserAccountService;
import cn.nkpro.elcube.security.bo.UserDetails;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 1、使用用户名密码获取token
 */
@Component
@Slf4j
@Order(2000)
public class NkLoginPasswordAuthenticationFilter extends GenericFilterBean implements AuthenticationFilterV2 {

    @Autowired
    private AuthenticationUtils authenticationUtils;
    @Autowired
    private UserAccountService userDetailsService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {

                // 区分客户端
                String client    = authenticationUtils.obtainParam(request, "client");
                // 用户名
                String username  = authenticationUtils.obtainParam(request, "username");
                // 请求时间戳，验证签名有效期
                String timestamp = authenticationUtils.obtainParam(request, "timestamp");
                // 签名，验证密码
                String password  = authenticationUtils.obtainParam(request, "password");

                if (StringUtils.isNoneBlank(client, username, timestamp, password)) {
                    try {
                        // 1、校验时间戳
                        AuthenticationUtils.validateTimestamp(timestamp);
                        // 2、校验错误登陆次数
                        String verKey    = authenticationUtils.obtainParam(request, "verKey");
                        String verCode   = authenticationUtils.obtainParam(request, "verCode");
                        authenticationUtils.validateErrorsLogin(username, true, verKey, verCode);

                        UserDetails details = (UserDetails) userDetailsService.loadUserByUsername(username);
                        AuthenticationUtils.simpleValidate(details);

                        // 验证密码
                        if(!StringUtils.equalsIgnoreCase(
                                DigestUtils.sha1Hex(String.format("password=%s&timestamp=%s",details.getPassword(), timestamp)),
                                password
                        )){
                            authenticationUtils.throwsErrorsLogin(username);
                        }

                        authenticationUtils.clearErrorsLogin(username);

                        AbstractAuthenticationToken responseAuthentication = new UsernamePasswordAuthenticationToken(
                                username,
                                null,
                                details.getAuthorities());
                        responseAuthentication.setDetails(details);

                        ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_OK);
                        response.setCharacterEncoding("utf-8");
                        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        PrintWriter printWriter = response.getWriter();
                        printWriter.print(authenticationUtils.grantToken(client,username));
                        printWriter.flush();
                        printWriter.close();
                    }catch (AuthenticationException e){
                        authenticationUtils.commence((HttpServletResponse)response, e);
                        return;
                    }
                }
            }
        }

        filterChain.doFilter(request, response);
    }
}
